<template>
  <div class="product-list">
    <t-enhanced-table
      rowKey="product_gid"
      :data="lists"
      :columns="columns"
      :stripe="stripe"
      :bordered="bordered"
      :hover="hover"
      :size="size"
      :height="maxHeight"
      :tree="{ childrenKey: 'relation', treeNodeColumnIndex: 0, expandTreeNodeOnClick: false, defaultExpandAll: true }"
      :table-layout="tableLayout ? 'auto' : 'fixed'"
      :showHeader="showHeader"
      cellEmptyContent="-"
      resizable
      :loading="loading"
    >
      <template #id="{row}">
        <p>{{ row.id }}</p>
      </template>
      <template #product_title="{row}">
        <div class="flex align-center">
          <div class="mr8">
            <t-image-viewer v-if="row.product_thumb" :images="[row.product_thumb]" :closeOnEscKeydown="false">
              <template #trigger="{ open }">
                <div class="tdesign-demo-image-viewer__ui-image" @click="open">
                  <p class="prod-img">
                    <img alt="test" :src="row.product_thumb"/>
                  </p>
                  <div class="tdesign-demo-image-viewer__ui-image--hover">
                    <span><browse-icon size="1.4em"/> </span>
                  </div>
                </div>
              </template>
            </t-image-viewer>
            <p v-else class="no-img"></p>
          </div>
          <div>
            <p>{{ row.product_title }}</p>
            <!--<p class="" style="font-size: 12px;color: rgba(0,0,0,0.7);">SN:1561565156165165</p>-->
          </div>
        </div>
      </template>
      <template #product_price="{row}">
        <p>￥{{ row.product_price }}</p>
      </template>
      <template #quantity="{row}">
        <t-popconfirm theme="default" :confirmBtn="null" :cancelBtn="null">
          <template #icon><p></p></template>
          <template #content>
            <div style="width: 560px">
              <t-table
                rowKey="id"
                :data="row.selectList"
                :columns="columns2"
                :stripe="stripe"
                :bordered="bordered"
                :hover="hover"
                :size="size"
                height="20vh"
                :table-layout="tableLayout ? 'auto' : 'fixed'"
                :showHeader="showHeader"
                cellEmptyContent="-"
                resizable
              >
                <template #options="{row: row2}">
                  <t-link theme="danger" hover="color" @click="handleDeleteSelect(row, row2)">删除</t-link>
                </template>
              </t-table>
            </div>
          </template>
          <t-tag theme="primary" variant="outline" style="cursor:pointer;">{{ row.count ? row.count : 0 }}/{{ row.quantity }}</t-tag>
        </t-popconfirm>
      </template>
      <template #total_price="{row}">
        <p>￥{{ row.total_price }}</p>
      </template>
      <template #options="{row}">
        <t-link theme="primary" hover="color" class="edit-btn-color" @click="handleSelect(row)">选择</t-link>
      </template>
    </t-enhanced-table>

    <div class="flex align-center justify-end pr16 pt16">
      <p class="mr16" v-if="info.is_all_pay !== 1">代理商未支付尾款，不可发货</p>
      <t-button theme="primary" :disabled="!(info.status === 1 && info.is_all_pay === 1)" @click="handleSend">发货</t-button>
      <!--<t-button theme="primary" @click="handleSend">发货</t-button>-->
    </div>
  </div>
</template>

<script lang="jsx">
import { EnhancedTable } from 'tdesign-vue';
import {ChevronRightIcon, ChevronDownIcon} from 'tdesign-icons-vue';
import { BrowseIcon } from "tdesign-icons-vue";
import SelectProduct from "@/pages/order/purchase-list/components/select-product.vue";

export default {
  name: "ProductList",
  props: {
    info: {
      type: Object,
      default: ()=> {}
    }
  },
  components: {SelectProduct, BrowseIcon},
  data() {
    return {
      lists: [],
      size: 'medium',
      tableLayout: false,
      stripe: false,
      bordered: false,
      hover: true,
      showHeader: true,
      columns: [
        {colKey: 'id', title: 'ID', width: 76},
        {colKey: 'product_title', title: '商品信息', width: 220, fixed: 'left', ellipsis: true},
        {colKey: 'product_price', title: '购买价', width: 100},
        {colKey: 'quantity', title: '数量', width: 80},
        {colKey: 'total_price', title: '小计', width: 120},
        {colKey: 'options', title: '', width: 80},
      ],
      maxHeight: '66vh',
      loading: false,


      columns2: [
        {colKey: 'warehouse_name', title: '所属仓库', width: 140, ellipsis: true},
        {colKey: 'sn', title: 'SN', width: 220, ellipsis: true},
        {colKey: 'count', title: '数量', width: 80},
        {colKey: 'options', title: '', width: 60},
      ],
      options: [
        { label: 'DJI MINI PRO', value: '2' },
        { label: 'DJI MINI03', value: '3' },
      ]
    }
  },
  watch: {
    info: {
      deep: true,
      handler(val) {
        this.lists = [...this.info.product]
      }
    }
  },
  computed: {
    // 可以使用同名插槽代替渲染函数：<template #treeExpandAndFoldIcon><icon /></template>
    treeExpandIcon() {
      // 自定义展开图标
      return this.treeExpandAndFoldIconRender;
    },
  },
  mounted() {
    this.lists = [...this.info.product]
  },
  methods: {
    onExpandedTreeNodesChange(expandedTreeNodes, context) {
      console.log(expandedTreeNodes, context);
    },
    treeExpandAndFoldIconRender(h, { type, row }) {
      return type === 'expand' ? <ChevronRightIcon /> : <ChevronDownIcon />;
    },
    handleSelect(row) {
      this.$emit('select', row)
    },
    handleSend() {
      //
      //this.$emit('send', [])
      //return

      const totalCount = this.lists.reduce((pre, cur)=> {return pre + cur.count;}, 0)
      const totalQuantity = this.lists.reduce((pre, cur)=> {return pre + cur.quantity;}, 0)
      for (let i = 0; i < this.lists.length; i++) {
        const item = this.lists[i];
        if (item.count < item.quantity) {
          this.$message.warning(`【${item.product_title}】数量不足`)
          return
        }
      }

      if (totalCount < totalQuantity) {
        this.$message.warning(`【${data.product_title}】关联产品数量不足`)
        return
      }

      const relationList = this.lists.filter(item=> item.relation.length)
      let data = {};
      for (let i = 0; i < relationList.length; i++) {
        const item = relationList[i];
        const relationTotalCount = item.relation.reduce((pre, cur)=> {return pre + cur.count;}, 0)
        const relationTotalQuantity = item.relation.reduce((pre, cur)=> {return pre + cur.quantity;}, 0)
        if (relationTotalCount < relationTotalQuantity) {
          data = item
          break;
        }
      }

      if (Object.keys(data).length) {
        this.$message.warning(`【${data.product_title}】关联产品数量不足`)
        return
      }

      const lists = [
        //{
        //  order_product_id: '', // 订单产品清单ID
        //  data: [
        //    {
        //      stock_id: '', // 库存ID
        //      quantity: '', // 已选数量
        //    },
        //}
      ]

      for (let i = 0; i < this.lists.length; i++) {
        const item = this.lists[i]
        lists.push({
          order_product_id: item.id,
          data: item.selectList.map(el=> ({ stock_id: el.warehouse_id, quantity: el.count }))
        })
        if (item.relation && item.relation.length) {
          for (let j = 0; j < item.relation.length; j++) {
            const relation = item.relation[j]
            lists.push({
              order_product_id: relation.id,
              data: relation.selectList.map(el=> ({ stock_id: el.warehouse_id, quantity: el.count }))
            })
          }
        }
      }

      this.$emit('send', lists)
    },
    // 选择的产品
    changeSelect(data) {
      const { type, p_product_id, product_id, lists, total } = data
      if (type === 'product') {
        const index = this.lists.findIndex(item=> item.product_id === product_id)
        this.lists[index].count = total
        this.lists[index].selectList = lists
      } else {
        const pIndex = this.lists.findIndex(item=> item.product_id === p_product_id)
        if (pIndex !== -1) {
          const index = this.lists[pIndex].relation.findIndex(item=> item.product_id === product_id)
          this.lists[pIndex].relation[index].count = total
          this.lists[pIndex].relation[index].selectList = lists
        }
      }

      console.log('lists', this.lists)
    },
    // 删除产品
    handleDeleteSelect(row, row2) {
      const index = row.selectList.findIndex(item=> item.gid === row2.gid)
      if (index !== -1) {
        row.selectList.splice(index, 1)
        row.count = row.selectList.reduce((pre, cur)=> {
          return pre + cur.count;
        }, 0)
      }
    }
  }
}
</script>

<style lang="less" scoped>
///deep/ .t-table__tree-col--inline {
//  display: flex;
//
//}
  .product-list {

  }
</style>
